﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Common.Tools
{
    /// <summary>
    /// 性能计数器
    /// 参考自:http://www.cnblogs.com/JeffreyZhao/archive/2009/03/10/codetimer.html
    /// </summary>
    public static class CodeTimer
    {
        public static PrintType PrintType = PrintType.Console;
        /// <summary>
        /// 在测试开始前调用。
        /// 首先它会把当前进程及当前线程的优先级设为最高，这样便可以相对减少操作系统在调度上造成的干扰。
        /// 然后调用一次Time方法进行“预热”，让JIT将IL编译成本地代码，让Time方法尽快“进入状态”。
        /// </summary>
        public static void Initialize(PrintType printType = PrintType.Console)
        {
            PrintType = printType;
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Time("", 0, () => { });
        }
        /// <summary>
        /// 测试方法
        /// </summary>
        /// <param name="name">测试名,为空时默认为Null</param>
        /// <param name="iteration">测试次数</param>
        /// <param name="action">测试方法(无参)</param>
        public static void Time(string name, int iteration, Action action)
        {
            //if (iteration < 1)
            //    return;
            if (String.IsNullOrEmpty(name))
                name = "Null";
            // 1.保留当前控制台前景色，并使用黄色输出名称参数。
            WriteLog(name);

            // 2.强制GC进行收集，并记录目前各代已经收集的次数。
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            int[] gcCounts = new int[GC.MaxGeneration + 1];
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                gcCounts[i] = GC.CollectionCount(i);
            }

            // 3.执行代码，记录下消耗的时间及CPU时钟周期。
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ulong cycleCount = GetCycleCount();
            for (int i = 0; i < iteration; i++)
                action();
            ulong cpuCycles = GetCycleCount() - cycleCount;
            watch.Stop();

            // 4.恢复控制台默认前景色，并打印出消耗时间及CPU时钟周期。
            WriteLog("--------Time Elapsed:\t" + watch.ElapsedMilliseconds.ToString("N0") + "ms");
            WriteLog("--------CPU Cycles:\t" + cpuCycles.ToString("N0"));

            // 5.打印执行过程中各代垃圾收集回收次数。
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                WriteLog("--------Gen " + i + ": \t\t" + count);
            }

            WriteLog(" ");
        }

        private static ulong GetCycleCount()
        {
            ulong cycleCount = 0;
            QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
            return cycleCount;
        }

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);

        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();

        private static void WriteLog(string msg)
        {
            if (string.IsNullOrEmpty(msg))
                return;
            if (PrintType == PrintType.Console)
                Console.WriteLine(msg);
            else
                Msg.Log.GetLog.Info(msg);
        }
    }
    public enum PrintType
    {
        Console,
        InfoLog
    }
}
